/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

 /***************************************************************************
 * Name: app_engine.cpp
 *
 * Purpose: app base functional helper API implementation.
 *
 * Developer:
 *   wen.gu , 2020-09-14
 *
 * TODO:
 *
 ***************************************************************************/

 /******************************************************************************
 **    INCLUDES
 ******************************************************************************/
#define LOG_TAG "APPE"
#include "panda/app/app_engine.h"

#include <map>
#include "panda/com/service_provider.h"
#include "panda/com/client_requester.h"

#include "panda/core/log.h"

namespace panda
{
namespace app
{
/******************************************************************************
 **    MACROS
 ******************************************************************************/

#define APP_MANAGER "app_manager"
/******************************************************************************
 **    VARIABLE DEFINITIONS
 ******************************************************************************/
using panda::com::ServiceProvider;
using panda::com::ServiceRequestHandlePtr;
using panda::com::ClientRequester;
using panda::core::Value;

using ProviderMap = std::map<std::string, ServiceProvider*>;

class AppEngine::impl
{
public:
    ProviderMap mProviders;
    ClientRequester* mClient = nullptr;
public:
    impl();
    ~impl();

public:
    ClientRequester* getClient();
    PandaErrc addServiceProider(const std::string& name, OnFocusChanged cb);
    PandaErrc requestFocus(const std::string& appName, AppRequestFocusType type, bool isDesktop);
};

/******************************************************************************
 **    inner FUNCTION DEFINITIONS
 ******************************************************************************/
static AppFocusState Str2FocusState(const std::string& focusState)
{
    if (focusState == "focus_on")
    {
        return AppFocusState::On;
    }
    else if (focusState == "focus_off")
    {
        return AppFocusState::Off;
    }
    else if (focusState == "coexistence_focus_off")
    {
        return AppFocusState::CoexistenceOff;
    }

    return AppFocusState::Unknown;
}



static std::string FocusType2Str(AppRequestFocusType type)
{
    if (type == AppRequestFocusType::Coexistence)
    {
        return "Coexistence";
    }
    else if (type == AppRequestFocusType::Exclusive)
    {
        return "Exclusive";
    }

    return "";
}

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

AppEngine::impl::impl()
{
}

AppEngine::impl::~impl()
{
    ProviderMap::iterator it = mProviders.begin();
    while (it != mProviders.end())
    {
        ServiceProvider* sp = it->second;
        if (sp)
        {
            sp->stop();
            delete sp;
        }

        ++it;
    }

    mProviders.clear();
}

ClientRequester* AppEngine::impl::getClient()
{
    if (mClient)
    {
        return mClient;
    }

    mClient = ClientRequester::getService(APP_MANAGER);

    return mClient;
}

AppEngine::PandaErrc AppEngine::impl::requestFocus(const std::string& appName, AppRequestFocusType type, bool isDesktop)
{

    ClientRequester* client = getClient();

    if (!client)
    {
        return PandaErrc::NoInit;
    }

    Value param;
    param["name"] = appName;
    param["type"] = FocusType2Str(type);
    param["is_desktop"] = isDesktop;

    Value reply;
    PandaErrc ret = client->request("requestFoucs", param, reply);

    if (PandaErrc::OK == ret)
    {
        ret = panda::core::Json2Error(reply);
    }

    return ret;

}

AppEngine::PandaErrc AppEngine::impl::addServiceProider(const std::string& name, OnFocusChanged cb)
{
    ProviderMap& pm = mProviders;
    ProviderMap::iterator it = pm.find(name);
    ServiceProvider* sp = nullptr;
    if (it == pm.end())
    {
        sp = new ServiceProvider(name);
    }
    else
    {
        sp = it->second;
    }

    if (sp)
    {
        sp->registerMethod("doFocusChange", [this, name, cb, sp](ServiceRequestHandlePtr srhdl, const std::string& method, const Value& param)
            {
                Value reply;
                if (param.isMember("name") && param.isMember("type"))
                {
                    std::string appName = param["name"].asString();

                    if (appName == name)
                    {
                        if (cb)
                        {
                            std::string focusState = param["type"].asString();
                            cb(appName, Str2FocusState(focusState));
                            panda::core::Error2Json(PandaErrc::OK, reply);
                        }
                        else
                        {
                            panda::core::Error2Json(PandaErrc::NotImplemented, reply);
                        }
                    }
                    else
                    {
                        panda::core::Error2Json(PandaErrc::Mismatch, reply);
                    }
                }
                else
                {
                    panda::core::Error2Json(PandaErrc::BadParameter, reply);
                }

                sp->sendResponse(srhdl, reply);
            });

        pm[name] = sp;
        return sp->start();  /** todo, process callbacks */
    }

    return PandaErrc::Undefined;
}


/******************************************************************************
 **    FUNCTION DEFINITIONS
 ******************************************************************************/
AppEngine::AppEngine()
    :mImpl(new impl)
{
    /** todo something */
}

AppEngine::~AppEngine()
{
    /** todo something */
}
//static 
AppEngine& AppEngine::get()
{
    static AppEngine ae;
    return ae;
}

AppEngine::PandaErrc AppEngine::requestFocus(OnFocusChanged cb, const std::string& name, AppRequestFocusType type, bool isDesktop /*= false*/)
{

    PandaErrc ret = mImpl->addServiceProider(name, cb);

    if (PandaErrc::OK != ret)
    {
        LOGE("add a app service for(%s) failed(%s)\n", name.c_str(), panda::core::ErrorStr(ret));
        return ret;
    }

    return mImpl->requestFocus(name, type, isDesktop);
}

void AppEngine::releaseFocus(const std::string& name)
{
    ClientRequester* client = mImpl->getClient();

    if (client)
    {
        Value param;
        Value reply;

        param["name"] = name;

        client->request("releaseFoucs", param, reply);
    }
}

} /** namespace app */
} /** namespace panda */
